import axios from "axios";
import path from 'path'
import fs from 'fs'


// 此文件暂时废弃

const llmTypes = {
  'ERNIE-3.5-8K': (token: string) => `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=${token}`,
  'ERNIE-Speed-8K': (token: string) => `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed?access_token=${token}`
}

export const llmFetch = async (type: keyof typeof llmTypes, content: string) => {
  let requestUrl = ''
  const token = await getLlmFetchToken()
  if (typeof llmTypes[type] == 'function') {
    requestUrl = llmTypes[type](token)
    return await axios({
      url: requestUrl,
      method: "POST",
      data: {
        messages: [
          { role: "user", content: content },
        ],
        temperature: 0.3,
      },
      headers: {
        "Content-Type": "application/json",
      },
    });
  } else {
    throw new Error('llm type not found')
  }
}

async function requestToken() {
  const { data } = await axios({
    url: `https://aip.baidubce.com/oauth/2.0/token`,
    method: "post",
    headers: {
      "Content-Type": "application/json",
    },
    data: {},
    params: {
      client_id: 'xxx',
      client_secret: 'xxx',
      grant_type: 'xxxx',
    },
  });
  return data;
}

const getLlmFetchToken = async (force: boolean = false) => {
  const catchDir = path.join(process.cwd(), ".catch");
  fs.existsSync(catchDir) || fs.mkdirSync(catchDir);
  if (fs.existsSync(path.join(catchDir, "./proxy-token"))) {
    const data = JSON.parse(fs.readFileSync(path.join(catchDir, "./proxy-token"), "utf-8"));
    if (data.expire > parseInt(String(new Date().getTime() / 1000)) && !force) {
      return data.token;
    }
  }
  const data = await requestToken();
  if (data.access_token) {
    fs.writeFileSync(
      path.join(catchDir, "./proxy-token"),
      JSON.stringify({
        token: data.access_token,
        expire: parseInt(String(new Date().getTime() / 1000)) * 1 + data.expires_in,
      })
    );
    return data.access_token;
  } else {
    throw new Error(data)
  }
};



/**
 * 变量名转换
 * @param str 
 * @returns 
 */
export const getVariableName = async (str: string) => {
  const response = await llmFetch('ERNIE-Speed-8K', `
  # 角色
  你是一个专业的变量名生成器，能够根据程序员提供的具体场景，生成符合计算机语言开发范式、易读且地道的英文变量或方法名。
  ## 示例
  \`\`\`
  # 输入
  我是测试中文
  # 输出
  testChinese
  \`\`\`
  小驼峰生成变量名: \`${str}\`
`);
  return response.data.result
}



export const getVariableArrName = async (strArr: string[]): Promise<string[]> => {
  strArr = strArr.map(item => {
    return item.replace(/[^\u4e00-\u9fa5\d]/g, '')
  })
  console.log('strArr', strArr);
  const response = await llmFetch('ERNIE-Speed-8K', `
  You are a service that translates user requests into Array objects of type  according to the following TypeScript definitions 
   \`\`\`
   // 将下面数组根据 将值转为语义化且简短的首字母为小写的小驼峰英文变量名
   type arr = string[]
   \`\`\`
   The following is a user request: 
   """
   ${JSON.stringify(strArr)}
   """
   The following is the user request translated into a Array object with 2 spaces of indentation and no properties with the value undefined:
   eg:[]
   `);
  let text = response.data.result
  console.log(text);
  text = text.replace(/.*```json/, "").replace(/```.*/, "");
  console.log(text);
  return JSON.parse(text);
}